/*ui_mask编辑*/
(function ($) {
    $.fn.yqAttrEdit = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqAttrEdit.methods[opts](this, param);
        }

        return this.each(function () {
            $this = $(this);
            var opt = $.extend({}, $.fn.yqAttrEdit.defaults, opts);
            if ($this.data("yqtype") == "yqAttrEdit") {
                var $uniqueID = $this.attr("ID");
                destroy($this);
                $this = $("#" + $uniqueID);
            }
            else {
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined || $uniqueID === null || $uniqueID == "") {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            if (opt.editModeW === undefined && $this.width() > 0) {
                opt.editModeW = $this.width();
            }
            else if (typeof opt.editModeW != "undefined") {
                $this.width(opt.editModeW);
            }

            if (opt.editModeH === undefined && $this.height() > 0) {
                opt.editModeH = $this.height();
            }
            else if (typeof opt.editModeH != "undefined") {
                $this.height(opt.editModeH);
            }

            //变量信息
            $this.data("attredit_opt", opt);
            $this.data("yqtype", "yqAttrEdit");

            opt.loadui = false;

            opt.fk_rows = [];

            init_pg_before($this);
        });
    };

    $.fn.yqAttrEdit.defaults = {
        ajaxUrl: "/_db.html",
        titles: [],
        action: "add",
        row: {},
        // editModeW: 500,      //模态编辑器宽度 格式为 800（数字）
        // editModeH: 300,      //模态编辑器高度 格式为 600（数字）
        loadDefault: false,   //加载默认值
        isEdit: true,
        blankTag: "*",     //值不能为空，标题附加标记
        removeUnUse: false, //是否移除未使用的字段
        beforeBindingTitle: function (titles, callback) {
            callback(titles);
        }, //标题绑定前
        afterBindingTitle: function () { },   //标题绑定后
        endEditing: function (index, row) {   //ok.....

        },
    };

    $.fn.yqAttrEdit.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        setTitles: function (jq, titles) {
            options(jq).titles = titles;
        },
        setRow: function (jq, row) {   //{"ui_type":2,"value":""}
            setRow($(jq[0]), row);
        },
        clear: function (jq) {   //{"ui_type":2,"value":""}
            setRow($(jq[0]), {});
        },
        getRow: function (jq) {
            return getRow($(jq[0]));
        },
        isEdit: function (jq, tf) {
            isEdit($(jq[0]), tf);
        },
        resize: function (jq, params) {
            resize($(jq[0]), params);
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        setField: function (jq, para) {
            if (para === undefined) {
                return;
            }
            if (para.name === undefined) {
                return;
            }
            if (para.value === undefined) {
                return;
            }

            setfield(jq, para.name, para.value)
        }
    };

    function options($object) {
        return $object.data("attredit_opt");
    }

    function resize($object, params) {
        var opt = options($object);
        if (typeof params == "object") {
            opt.width = params.width;
            opt.height = params.height;
        }

        $object.propertygrid("resize", {
            width: opt.width,
            height: opt.height
        });
    }

    function destroy($object) {
        var opt = options($object);
        var $uniqueID = $object.attr("id");

        var $div = $object.closest("div.datagrid");
        $div.after($object);
        $object.show();
        $div.remove();
        $object.removeClass("datagrid-f");

        $object.removeData("attredit_opt");
        $object.removeData("yqtype");

        var $table = $("<table></table>");
        $table.css({ width: opt.editModeW, height: opt.editModeH });
        $object.before($table);
        $object.remove();
        $table.attr("id", $uniqueID);
    }

    function init_pg_before($object) {
        var opt = options($object);
        opt.beforeBindingTitle.call($object, opt.titles,
            function (titles) {
                opt.titles = titles;
                init_pg($object);
            });
    }

    function init_pg($object) {
        var opt = options($object);

        opt.titles = $.yqFmUiTitle(opt.titles);
        opt.hasGroup = false;
        for (let i = 0; i < opt.titles.length; i++) {
            if (opt.titles[i]["group"] != "") {
                opt.hasGroup = true;
                break;
            }
        }

        var _width1 = parseInt(opt.editModeW * 0.35);
        var _width2 = opt.editModeW - _width1 - 35;
        if (_width1 < 50) {
            _width1 = 50;
        }
        if (_width2 < 50) {
            _width2 = 50;
        }
        var g_opt = {
            columns: [[
                {
                    field: 'name', title: '名称', width: _width1 + 'px'
                }, {
                    field: 'value',
                    title: '值',
                    width: _width2 + 'px',
                    formatter: function (value, row, index) {
                        this.p_target = $object;
                        return $.yqPgFormatter.call(this, {
                            value: value,
                            row: row,
                            index: index,
                            field: "value",
                            ui_type: row.ui_type,
                            ui_mask: row.ui_mask
                        });
                    }
                }
            ]],
            // groupFormatter:function(group,rows){
            //     console.log(group,rows);  
            // },
            scrollbarSize: 0,
            onBeforeEdit: function (index, row) {
                $(this).propertygrid("options")._before_index = index;
                $(this).propertygrid("options")._before_value = row["value"];
            },
            onAfterEdit: function (index, row, changes) {
                if (row.ui_type == 8) {
                    if ($(this).propertygrid("options")._before_value == row["value"]) {
                        return;
                    }

                    if (row.ui_mask.subfield != "") {
                        var c_value = -1;
                        if (!(changes.value === null)) {
                            c_value = parseInt(changes.value);
                            if (isNaN(c_value)) {
                                c_value = -1;
                            }
                        }

                        var subfield = row.ui_mask.subfield;

                        var e_rows = $(this).propertygrid("getRows");
                        while (subfield != "") {
                            var hasrow = false;
                            for (var e = 0; e < e_rows.length; e++) {
                                if (e_rows[e].ui_type == 8 && e_rows[e].field == subfield) {
                                    subfield = e_rows[e].ui_mask.subfield;
                                    hasrow = true;
                                    e_rows[e].value = -1;
                                    break;
                                }
                            }

                            if (hasrow == false) {
                                subfield = "";
                            }
                        }

                        $(this).propertygrid("loadData", e_rows);
                    }
                }

                delete $(this).propertygrid("options")._before_index;
                delete $(this).propertygrid("options")._before_value;
            },
            onEndEdit: function (index, row, changes) {
                //opt.endEditing.call($object,index,row);
            }
        };

        if (opt.hasGroup) {
            g_opt.showGroup = true;
            g_opt.groupField = "group";
        }

        $object.propertygrid(g_opt);
        $object.propertygrid("loadData", loadData($object));
        opt.loadui = true;

        opt.afterBindingTitle.call($object);

        if (Object.getOwnPropertyNames(opt.row).length > 0) {
            var row = opt.row;
            if (opt.loadDefault && opt.action == "add") {
                row = $.extend($.yqGetDefaultRow(opt.titles), row);
            }
            setRowRun($object, row, false);
        } else if (opt.loadDefault) {
            setRowRun($object, $.yqGetDefaultRow(opt.titles), false);
        }
    }

    function loadData($object) {
        var opt = options($object);
        var rows = [];
        if (opt.row === undefined || opt.row === null || opt.row == "") {
            opt.row = {};
        }
        for (let i = 0; i < opt.titles.length; i++) {
            var title = opt.titles[i];
            var value = opt.row[title.name];
            if (value === undefined) {
                value = null;
            }

            if (!title.is_func && title.ui_visible) {

                var row = {
                    field: title.name,
                    name: (title.ui_type == 3 || title.ui_mask.blank) ? title.ui_title : (opt.blankTag + title.ui_title),
                    value: value
                };

                if (opt.hasGroup) {
                    row.group = title.group;
                }

                if (!title.ui_readonly && opt.isEdit) {
                    row = $.yqDgEditor(row, title.ui_type, title.ui_mask)
                }
                else {
                    row.ui_type = title.ui_type;
                    row.ui_mask = title.ui_mask;
                }

                rows.push(row);
            }
        }
        return rows;
    }

    function endEditing($object) {
        var _opt = $object.propertygrid("options");
        if (typeof _opt._before_value != "undefined") {
            $object.propertygrid('endEdit', _opt._before_value);
            delete _opt._before_value;
        }
    }

    function setRow($object, row) {
        var opt = options($object);

        if (opt.loadui) {
            setRowRun($object, row, true);
        }
        else {
            setTimeout(function () {
                setRow($object, row);
            }, 500);
        }
    }

    function setRowRun($object, row, tf) {
        var opt = options($object);
        if (tf === undefined) {
            tf = true;
        }
        if (tf) {
            opt.row = row;
        }

        setForienKeys($object, opt.row, function () {
            var rows = $object.propertygrid("getRows");
            for (let i = 0; i < rows.length; i++) {
                var val = row[rows[i].field];
                if (val === undefined) {
                    val = null;
                }
                rows[i].value = val;
            }
            endEditing($object);
            $object.propertygrid("loadData", rows);
        });
    }

    function getRow($object) {
        var opt = options($object);
        $object.datagrid('acceptChanges');
        var rows = $object.propertygrid("getRows");

        var _row = {};

        for (let i = 0; i < rows.length; i++) {
            val = rows[i]["value"];
            if (typeof val === undefined) {
                _row[rows[i]["field"]] = null;
            } else {
                _row[rows[i]["field"]] = val;
            }
        }

        var row = $.extend(opt.row, _row);

        if (opt.removeUnUse) {
            var _row = {};
            for (let i = 0; i < opt.titles.length; i++) {
                var title = opt.titles[i];
                if (row.hasOwnProperty(title.name)) {
                    _row[title.name] = row[title.name];
                }
            }
            row = _row;
        }

        return row;
    }

    //设置行值
    function setfield($object, name, val) {
        var opt = options($object);
        if(val === undefined){
            val = null;
        } 
        if(val === null){
           delete opt.row[name];
        }else{
            opt.row[name]=val;
        }

        var rows = $object.propertygrid("getRows");
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].field == name) {
                $object.propertygrid("updateRow", {
                    index: i,
                    row: {
                        value: val
                    }
                });
                return;
            }
        }
    }

    function isEdit($object, tf) {
        var opt = options($object);
        opt.isEdit = tf;
        endEditing($object);
        $object.propertygrid("loadData", loadData($object));
    }

    function setForienKeys($object, row, callback) {
        var opt = options($object);
        var rows = [];
        rows.push(row);
        var opts = {
            "ajaxUrl": opt.ajaxUrl,
            "rows": rows,
            "titles": opt.titles,
            "fk_rows": opt.fk_rows === undefined ? [] : opt.fk_rows
        };

        $.yqGetForeignkeys(opts,
            function (fk_rows) {
                opt.fk_rows = fk_rows;
                callback();
            });
    }
})(jQuery);

